import { Notification } from "element-ui";
import { getUserInfoByIscTicket } from "../api/user";
import router from "../router/index";
import store from "../store";
import { getOrgDepartmentName } from "@/api/common.js";
import { getMenuTreeByRole } from "@/api/SystemConfig/menuConfig.js";
// ISC测试环境
const ISC_PREFIX_API = process.env.VUE_APP_ISC_URL;

// ISC生产环境
// const ISC_PREFIX_API = ''

// ISC url
const loginUrl = ISC_PREFIX_API + "/isc_sso/login";
const logoutUrl = ISC_PREFIX_API + "/isc_sso/logout";

// 完整登录 isc url
export const ISC_LOGIN_URL = loginUrl + "?service=";

// 完整登出 isc url
export const ISC_LOGOUT_URL = logoutUrl + "?service=";
// 运行环境
const nodeEnv = process.env.NODE_ENV;

const judgeISC = () => {
  const addr = window.location.href;
  const url = addr.substring(0, addr.indexOf("/", addr.indexOf("/") + 2)) + "/hb-ecs";
  if (addr.indexOf("?ticket") < 0) {
    window.location.href = ISC_LOGIN_URL + url;
  } else if (addr.indexOf("?ticket") > 0) {
    const token = addr.substring(addr.indexOf("?ticket=") + 8);
    getUserInfoByIscTicket(token).then(res => {
      if (res) {
        getMenuTreeByRole(res.roleId).then(menuConfig => {
          const org = {
            orgCode: res.orgId,
            orgId: res.orgId,
            orgName: res.orgName,
            departmentName: res.superiorDept,
            unitName: res.unitName,
            level: Number(res.level),
            superiorDeptId: res.superiorDeptId,
            superiorDept: res.superiorDept,
            ssbmId: res.ssbmId,
            ssbmName: res.ssbmName
          };
          getOrgDepartmentName(org.orgId).then(dwbm => {
            let dwbmName = "";
            if (dwbm.includes("/")) {
              const arr = dwbm.split("/");
              dwbmName = arr.join("");
            } else {
              dwbmName = dwbm;
            }
            sessionStorage.setItem("dwbmName", dwbmName);
          });
          const role = {
            roleCode: res.roleCode,
            roleId: res.roleId,
            roleName: res.roleName
          };
          const account = {
            id: res.id,
            realName: res.realName
          };
          sessionStorage.setItem("org", JSON.stringify(org));
          sessionStorage.setItem("role", JSON.stringify(role));
          sessionStorage.setItem("account", JSON.stringify(account));
          sessionStorage.setItem("accessToken", JSON.stringify(res.accessToken));
          store.commit("SET_MenuIndex", 1);
          store.commit("UPDATE_IscLoginStatus", 1);
          if (menuConfig.length > 0) {
            // 去掉系统配置菜单下的子模块内容
            const result = menuConfig.map(i => {
              if (i.menuName === "系统配置") {
                i.children = [];
              }
              return i;
            });
            store.commit("SET_MenuTree", result);
            Notification({
              message: "登录成功",
              type: "success"
            });
            router.push({ path: result[0].menuUrl });
            if (result[0].parent && result[0].parent != "1480016250535968") {
              store.commit("SET_MenuIndex", result[0].parent);
            } else {
              store.commit("SET_MenuIndex", result[0].id);
            }
          } else {
            Notification({
              message: "当前账号角色没有菜单权限，请先配置菜单",
              type: "warning"
            });
            clearOut();
          }
        });
      }
    });
  }
};

const clearOut = () => {
  sessionStorage.clear();
  setTimeout(() => {
    if (["localhost"].includes(window.location.hostname)) {
      window.location.href = `${window.location.origin}/hb-ecs/Login`;
    } else {
      window.location.href = `${ISC_LOGOUT_URL}${window.location.origin}`;
    }
  }, 1000);
};

export default { judgeISC, nodeEnv };
